<template>
  <div>
    <!-- 头部 -->
    <nav-bar>
      <template v-slot:default>新用户注册</template>
    </nav-bar>

    <!-- 图片 -->
    <div style="margin: 45px;">
      <div style="text-align: center;">
        <img src="../../assets/images/empty-car.png" alt="" style="width:200px;">
      </div>
    </div>

    <!-- 表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="name"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
        v-model="password_confirmation"
        type="password"
        name="确认密码"
        label="确认密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写一致密码' }]"
      />
      <van-field
        v-model="email"
        name="电子邮箱"
        label="电子邮箱"
        placeholder="电子邮箱"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <div style="margin: 16px;">
        <div class="link-login" @click="$router.push('/login')">
          已有账号，立即登录
        </div>
        <van-button round block type="primary" native-type="submit">注册</van-button>
      </div>
    </van-form>


  </div>
</template>

<script>
import { register} from 'network/user.js'
import NavBar from 'components/common/navbar/NavBar.vue';
import {useRouter} from 'vue-router'
import { reactive, toRefs } from 'vue';
import { Notify, Toast } from 'vant';
export default {
  name: 'Register',
  setup () {
    const router = useRouter()

    // 用户注册填写的信息
    const userInfo = reactive({
      name: '',
      password: '',
      password_confirmation: '',
      email: ''
    })

    // 提交事件
    const onSubmit = async () => {
      // 先验证
      if(userInfo.password !== userInfo.password_confirmation) {
        Notify('两次输入密码不一致！')
      } else {
        // 再提交数据，请求注册
        const data = await register(userInfo)
        // 用户：zhu， 密码：zhu123， 邮箱：zhu123456@qq.com
        if(data.status === 201) {
          Toast.success('注册成功！')
          setTimeout(()=>{
            router.push('/login')
          },1000)
        }
        userInfo.password = ''
        userInfo.password_confirmation = ''

      }
      

    }

    return {
      ...toRefs(userInfo),
      onSubmit
    };
  },

  components: {
    NavBar,
  }
}

</script>
<style lang='scss' scoped>
.link-login {
  width: 37%;
  font-size: 14px;
  margin-bottom: 20px;
  color: #42b983;
  text-align-last: left;
}
</style>